package com.kaiwukj.android.ufamily.mvp.ui.page.account.login.vcode;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.Group;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.VCodeEvent;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.login.LoginWayAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.login.LoginWayItemEntity;
import com.kaiwukj.android.ufamily.mvp.ui.widget.CodeEditText;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.UserStore;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


public class LoginVCodeIndexFragment extends BaseFragment {

    @BindView(R.id.group_input)
    Group groupInput;
    @BindView(R.id.et_code)
    CodeEditText codeEditText;
    @BindView(R.id.tv_code_time)
    TextView tvCodeTime;//计时器
    @BindView(R.id.btn_code_reply)
    Button btnCodeReply;//重新获取
    @BindView(R.id.et_phone_number)
    EditText etPhoneNum;
    @BindView(R.id.tv_phone_flag)
    TextView tvPhoneFlag;
    @BindView(R.id.iv_phone_clear)
    ImageView ivPhoneClear;

    @BindView(R.id.rv_login_way)
    RecyclerView rvLoginWay;

    private int flag = 0;
    private String phone;

    public int getFlag() {
        return flag;
    }

    @OnClick({R.id.tv_login, R.id.tv_login_code, R.id.btn_code_reply})
    void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                phone = etPhoneNum.getText().toString().trim();
                if (!RegexUtils.isMobileSimple(phone)) {
                    showMessage("输入正确的手机号");
                    return;
                }
                EventBus.getDefault().post(new VCodeEvent(VCodeEvent.SEND, phone));
                // start(LoginVCodeIndexFragment.newInstance(1));
                break;
            case R.id.btn_code_reply:
                if (!RegexUtils.isMobileSimple(phone)) {
                    showMessage("输入正确的手机号");
                    return;
                }
                startTimer();
                EventBus.getDefault().post(new VCodeEvent(VCodeEvent.RE_SEND, phone));
                break;
            case R.id.tv_login_code:
                if (RegexUtils.isMobileExact(phone)) {
                    ARouter.getInstance().build(ARouterUrlKt.LoginRouterUrl)
                            .withString("phone", phone)
                            .navigation();
                } else {
                    ARouter.getInstance().build(ARouterUrlKt.LoginRouterUrl)
                            .navigation();
                }
                break;

            default:
                throw new IllegalStateException("Unexpected value: " + view.getId());
        }
    }


    public static LoginVCodeIndexFragment newInstance(int flag) {
        Bundle bundle = new Bundle();
        bundle.putInt("flag", flag);
        LoginVCodeIndexFragment fragment = new LoginVCodeIndexFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public static LoginVCodeIndexFragment newInstance(int flag, String phone) {
        Bundle bundle = new Bundle();
        bundle.putInt("flag", flag);
        LoginVCodeIndexFragment fragment = new LoginVCodeIndexFragment();
        fragment.phone = phone;
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() == null) return;
        flag = getArguments().getInt("flag");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_login_vcode;
    }

    @Override
    protected void initView() {
        if (flag == 0) {
            if (!StringUtils.isEmpty(UserStore.getUName())) {
                etPhoneNum.setText(UserStore.getUName());
                ivPhoneClear.setVisibility(View.VISIBLE);
            }
            groupInput.setVisibility(View.VISIBLE);
            rvLoginWay.setVisibility(View.VISIBLE);
            rvLoginWay.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
            rvLoginWay.addItemDecoration(new SpaceItemDecoration(45, RecyclerView.HORIZONTAL));
            List<LoginWayItemEntity> loginWayItemEntities = new ArrayList<>();
            loginWayItemEntities.add(new LoginWayItemEntity(LoginWayItemEntity.WECHAT, R.mipmap.ic_login_way_wechat, "微信"));
            loginWayItemEntities.add(new LoginWayItemEntity(LoginWayItemEntity.ONEKEY, R.mipmap.ic_login_way_fast, "一键登录"));
            LoginWayAdapter loginWayAdapter = new LoginWayAdapter(loginWayItemEntities);
            rvLoginWay.setAdapter(loginWayAdapter);
            ivPhoneClear.setOnClickListener(v -> etPhoneNum.setText(""));
            etPhoneNum.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (count > 0) {
                        ivPhoneClear.setVisibility(View.VISIBLE);
                    } else {
                        ivPhoneClear.setVisibility(View.GONE);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
            loginWayAdapter.setOnItemClickListener((adapter, view, position) -> {
                switch (loginWayAdapter.getLoginWay(position)) {
                    case LoginWayItemEntity.WECHAT:
                        //showMessage("微信登录");
                        EventBus.getDefault().post(new VCodeEvent(VCodeEvent.LOGIN_WECHAT));
                        break;
                    case LoginWayItemEntity.ONEKEY:
                        EventBus.getDefault().post(new VCodeEvent(VCodeEvent.LOGIN_FAST));
                        // showMessage("一键登录");
                        break;
                }
            });
        } else {
            rvLoginWay.setVisibility(View.GONE);
            codeEditText.setVisibility(View.VISIBLE);
            btnCodeReply.setVisibility(View.GONE);
            tvCodeTime.setVisibility(View.VISIBLE);
            tvPhoneFlag.setVisibility(View.GONE);
            codeEditText.setOnTextFinishListener((text, length) -> {
                EventBus.getDefault().post(new VCodeEvent(VCodeEvent.CHECK, text.toString()));
            });
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (flag == 1) {
            startTimer();
        }
    }

    private void startTimer() {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(60)
                .doOnSubscribe(a -> {
                    tvCodeTime.setVisibility(View.VISIBLE);
                    btnCodeReply.setVisibility(View.GONE);
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        subscribe(d);
                    }

                    @Override
                    public void onNext(Long s) {
                        int ms = (int) (59 - s);
                        tvCodeTime.setText(String.format("%sS后重新发送", ms));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        tvCodeTime.setVisibility(View.GONE);
                        btnCodeReply.setVisibility(View.VISIBLE);
                    }
                });
    }

}
